<template>
  <div class="pet-adoption-list">
    <h2 class="title">宠物待领养</h2>

    <!-- 查询框部分 -->
    <div class="filters">
      <input v-model="searchQuery" type="text" placeholder="搜索宠物..." />
      <div class="filters-dropdown">
        <label for="type-select">种类：</label>
        <select v-model="selectedType" id="type-select">
          <option value="">全部</option>
          <option value="狗">狗</option>
          <option value="猫">猫</option>
          <option value="其它">其它</option>
        </select>
      </div>
      <div v-if="selectedType === '猫'" class="filters-dropdown">
        <label for="cat-breed-select">猫的品种：</label>
        <select v-model="selectedCatBreed" id="cat-breed-select">
          <option value="">全部</option>
          <option value="蓝白">蓝白</option><option value="蓝猫">蓝猫</option><option value="纯白">纯白</option><option value="虎斑">虎斑</option><option value="加白">加白</option>
          <option value="橘猫">橘猫</option><option value="黑猫">黑猫</option><option value="白猫">白猫</option><option value="布偶">布偶</option><option value="缅因">缅因</option>
          <option value="豹猫">豹猫</option><option value="金渐层">金渐层</option><option value="银渐层">银渐层</option><option value="狸花猫">狸花猫</option><option value="奶牛猫">奶牛猫</option>
          <option value="三花猫">三花猫</option><option value="波斯猫">波斯猫</option><option value="金吉拉">金吉拉</option><option value="拿破仑">拿破仑</option><option value="无毛猫">无毛猫</option>
          <option value="矮脚猫">矮脚猫</option><option value="暹罗猫">暹罗猫</option><option value="德文卷毛">德文卷毛</option><option value="美国卷耳">美国卷耳</option><option value="挪威森林">挪威森林</option>
          <option value="其它">其它</option>
        </select>
      </div>
      <div v-if="selectedType === '狗'" class="filters-dropdown">
        <label for="dog-breed-select">狗的品种：</label>
        <select v-model="selectedDogBreed" id="dog-breed-select">
          <option value="">全部</option>
          <option value="比熊">比熊</option><option value="泰迪">泰迪</option><option value="博美">博美</option><option value="柴犬">柴犬</option><option value="柯基">柯基</option>
          <option value="金毛">金毛</option><option value="边牧">边牧</option><option value="松狮">松狮</option><option value="巴哥">巴哥</option><option value="德牧">德牧</option>
          <option value="法斗">法斗</option><option value="西高地">西高地</option><option value="哈士奇">哈士奇</option><option value="蝴蝶犬">蝴蝶犬</option><option value="约克夏">约克夏</option>
          <option value="萨摩耶">萨摩耶</option><option value="雪纳瑞">雪纳瑞</option><option value="马尔济斯">马尔济斯</option><option value="拉布拉多">拉布拉多</option><option value="阿拉斯加">阿拉斯加</option>
          <option value="其它">其它</option>
        </select>
      </div>
      <div v-if="selectedType === '其它'" class="filters-dropdown">
        <label for="dog-breed-select">其它动物：</label>
        <select v-model="selectedOtherBreed" id="dog-breed-select">
          <option value="">全部</option>
          <option value="兔">兔</option><option value="仓鼠">仓鼠</option><option value="鹦鹉">鹦鹉</option><option value="龙猫">龙猫</option><option value="刺猬">刺猬</option>
          <option value="鸭">鸭</option><option value="小香猪">小香猪</option><option value="其它">其它</option>
        </select>
      </div>
      <div class="filters-dropdown">
        <label for="location-select">地区：</label>
        <select v-model="selectedLocation" id="location-select">
          <option value="">全部</option>
          <option value="北京">北京</option><option value="天津">天津</option><option value="上海">上海</option><option value="重庆">重庆</option>
          <option value="江苏">江苏</option><option value="浙江">浙江</option><option value="江西">江西</option><option value="黑龙江">黑龙江</option><option value="新疆">新疆</option>
          <option value="香港">香港</option><option value="澳门">澳门</option><option value="广东">广东</option><option value="广西">广西</option>
          <option value="湖南">湖南</option><option value="湖北">湖北</option><option value="辽宁">辽宁</option><option value="宁夏">宁夏</option>
          <option value="河南">河南</option><option value="河北">河北</option><option value="山东">山东</option><option value="山西">山西</option>
          <option value="内蒙古">内蒙古</option><option value="吉林">河北</option><option value="安徽">安徽</option>
          <option value="青海">青海</option><option value="甘肃">甘肃</option><option value="陕西">陕西</option>
          <option value="福建">福建</option><option value="海南">海南</option><option value="台湾">台湾</option><option value="海外">海外</option>
        </select>
      </div>
      <div class="filters-dropdown">
        <label for="age-sort">年龄排序：</label>
        <select v-model="ageSortOrder" id="age-sort">
          <option value="asc">年龄从小到大</option>
          <option value="desc">年龄从大到小</option>
        </select>
      </div>
      <div class="filters-dropdown">
        <label for="adopted-select">是否领养：</label>
        <select v-model="isAdoptedFilter" id="adopted-select">
          <option value="">全部</option>
          <option value="1">已领养</option>
          <option value="0">待领养</option>
          <option value="2">正在申请中</option>
        </select>
      </div>
    </div>

    <!-- 没有符合条件的宠物 -->
    <div v-if="filteredPets.length === 0">
      <p>目前没有符合条件的待领养宠物。</p>
    </div>

    <!-- 展示宠物信息 -->
    <div v-else class="pet-card" v-for="pet in filteredPets" :key="pet.id">
      <div class="pet-card-header">
        <h3>{{ pet.petname }}</h3>
        <span class="pet-type">{{ pet.pettype }}</span>
      </div>
      <div class="pet-card-body">
        <p><strong>年龄：</strong>{{ pet.age }}岁</p>
        <p><strong>疫苗接种：</strong>{{ pet.vaccinated ? '已接种' : '未接种' }}</p>
        <p><strong>疫苗名称：</strong>{{ pet.breed || '无' }}</p>
        <p><strong>地区：</strong>{{ pet.location }}</p>
        <p><strong>品种：</strong>{{ pet.breed || '未知' }}</p>
        <p><strong>发布人：</strong>{{ pet.ownername }}</p>
        <p><strong>是否已领养：</strong>{{ pet.adopted ? '已领养' : '待领养' }}</p>

        <!-- 领养按钮逻辑 -->
        <button v-if="pet.adopted =='0'" @click="applyForAdoption(pet.id)" style="background-color: #0084ff">申请领养</button>
        <button v-if="pet.adopted =='1'"  disabled>已领养</button>
        <button v-if="pet.adopted =='2'" disabled>已经被申请，审核中.....</button>
        <button v-if="pet.hasApplied == true " @click="cancelAdoption(pet)" style="background-color: #4CAF50">取消申请</button>

        <button @click="viewPetDetails(pet)" style="background-color: #e53935">查看详情</button>

      </div>
    </div>

    <!-- 宠物详情弹窗 -->
    <div v-if="selectedPet" class="pet-details-modal">
      <div class="modal-content">
        <h3>{{ selectedPet.petname }} - 详情</h3>
        <div class="pet-detail">
          <p><strong>宠物类型：</strong>{{ selectedPet.pettype }}</p>
          <p><strong>年龄：</strong>{{ selectedPet.age }}岁</p>
          <p><strong>描述：</strong>{{ selectedPet.petdescription }}</p>
          <p><strong>疫苗接种：</strong>{{ selectedPet.breed ? '已接种' : '未接种' }}</p>
          <p><strong>疫苗名称：</strong>{{ selectedPet.vaccineName || '无' }}</p>
          <p><strong>地区：</strong>{{ selectedPet.location }}</p>
          <p><strong>联系方式：</strong>{{ selectedPet.contact }}</p>
          <p><strong>品种：</strong>{{ selectedPet.breed || '未知' }}</p>
        </div>
        <button class="close-btn" @click="closePetDetails">关闭</button>
      </div>
    </div>
  </div>
</template>

<script>
import { findAllReceive,adopt,findAdopt ,cancelAdopt} from '../../api/user.js';

export default {
  data() {
    return {
      searchQuery: '',
      selectedType: '',
      selectedCatBreed: '',
      selectedDogBreed: '',
      selectedOtherBreed: '',
      selectedLocation: '',
      ageSortOrder: 'asc',
      isAdoptedFilter: '',
      selectedPet: null,
      pets: [],
      debouncedFetchPets: false,//是否是自己领养的，是就是
    };
  },
  watch: {
    // 监听 searchQuery 的变化
    searchQuery(newQuery) {
      this.debouncedFetchPets(newQuery);
    },
  },
  methods: {
    cancelAdoption(pet) {
      const user = JSON.parse(localStorage.getItem('user'));
      const username = user.nickname;

      const data = {
        id: pet.id,
        username: username
      };

      // 假设有一个取消领养的 API 方法叫做 cancelAdopt
      cancelAdopt(data).then(() => {
        alert('取消申请成功');
        this.fetchPet(); // 重新获取宠物列表以更新状态
      }).catch(error => {
        console.error('取消申请失败:', error);
      });
    },
    async fetchPet() {
      try {
        const response = await findAllReceive();
        console.log('Pets fetched successfully:', response.data);
        const user = JSON.parse(localStorage.getItem('user'));
        const username = user.nickname;
        console.log(username);
        // 遍历宠物列表，检查当前用户是否已经申请了该宠物
        this.pets = response.data.map(pet => {
          if (pet.adoptername == username && pet.adopted=='2') {
            pet.hasApplied = true; // 标记该宠物已被当前用户申请
          } else if(pet.adoptername === username&& pet.adopted=='2') {
           this.debouncedFetchPets=true
          } else
           {
            pet.hasApplied = false; // 标记该宠物未被当前用户申请
          }
          return pet;
        });
      } catch (error) {
        console.error('Error fetching pets:', error);
      }
    },
    applyForAdoption(petId) {
      const user = JSON.parse(localStorage.getItem('user'));
      const username = user.nickname;

      const data = {
        id: petId,
        username: username
      };

      adopt(data).then(() => {
        alert('申请成功');
        this.fetchPet(); // 重新获取宠物列表以更新状态
      }).catch(error => {
        console.error('申请失败:', error);
      });
    },
    viewPetDetails(pet) {
      this.selectedPet = pet; // 将选中的宠物赋值给 selectedPet
    }, closePetDetails() {
      this.selectedPet = null; // 关闭弹窗时清空 selectedPet
    },
    // 防抖函数
    debounce(func, wait) {
      let timeout;
      return function (...args) {
        clearTimeout(timeout);
        timeout = setTimeout(() => {
          func.apply(this, args);
        }, wait);
      };
    },
    // 获取宠物数据
    async fetchPets(query = '') {
      try {
        const response = await findAllReceive({ query }); // 假设 API 支持 query 参数
        this.pets = response.data;
      } catch (error) {
        console.error('Error fetching pets:', error);
      }
    },
    // 其他方法...
  },
  computed: {
    filteredPets() {
      return this.pets
          .filter((pet) => {
            const isAdopted = pet.adopted.toString();
            return (
                (!this.searchQuery || pet.petname.includes(this.searchQuery)) &&
                (!this.selectedType || pet.pettype === this.selectedType) &&
                (!this.selectedCatBreed || pet.breed === this.selectedCatBreed) &&
                (!this.selectedDogBreed || pet.breed === this.selectedDogBreed) &&
                (!this.selectedOtherBreed || pet.breed === this.selectedOtherBreed) &&
                (!this.selectedLocation || pet.location === this.selectedLocation) &&
                (this.isAdoptedFilter === '' || isAdopted === this.isAdoptedFilter)
            );
          })
          .sort((a, b) => {
            const ageA = Number(a.age);
            const ageB = Number(b.age);
            if (this.ageSortOrder === 'asc') {
              return ageA - ageB;
            } else {
              return ageB - ageA;
            }
          });
    },
  },
  created() {
    // 初始化防抖函数
    this.debouncedFetchPets = this.debounce(this.fetchPets, 300); // 300ms 防抖
  },
  mounted() {
    this.fetchPets();
    this.fetchPet();
   // 初始化加载数据
  },
};
</script>

  <style scoped>
  body {
    font-family: 'Arial', sans-serif;
    background-color: #f4f7fa;
    margin: 0;
    padding: 0;
  }

  .pet-adoption-list {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
    background-color: #fff;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    border-radius: 8px;
  }

  .title {
    font-size: 36px;
    text-align: center;
    color: #4f8a8b;
    margin-bottom: 20px;
  }

  /* 筛选区 */
  .filters {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    margin-bottom: 30px;
  }

  .filters .filters-dropdown {
    flex: 1 1 200px;
  }

  .filters input,
  .filters select {
    width: 100%;
    padding: 10px;
    font-size: 16px;
    border-radius: 6px;
    border: 1px solid #ccc;
    box-sizing: border-box;
  }

  .filters input {
    border-color: #4f8a8b;
  }

  .filters select {
    background-color: #f9f9f9;
  }

  /* 宠物卡片 */
  .pet-card {
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
    padding: 20px;
    transition: transform 0.3s ease, box-shadow 0.3s ease;
  }

  .pet-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2);
  }

  .pet-card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .pet-card-header h3 {
    font-size: 24px;
    color: #4f8a8b;
  }

  .pet-type {
    background-color: #e0f7fa;
    padding: 5px 10px;
    border-radius: 15px;
    color: #00796b;
  }

  .pet-card-body {
    margin-top: 10px;
  }

  .pet-card-body p {
    font-size: 16px;
    color: #555;
  }

  button {
    background-color: #4f8a8b;
    color: white;
    padding: 10px 20px;
    font-size: 16px;
    border-radius: 6px;
    border: none;
    cursor: pointer;
    transition: background-color 0.3s;
    margin: 0 10px;
  }

  button:hover {
    background-color: #00796b;
  }

  /* 宠物详情模态框 */
  .pet-details-modal {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    background: rgba(0, 0, 0, 0.5);
    z-index: 1000;
  }

  .modal-content {
    background-color: #fff;
    padding: 30px;
    border-radius: 8px;
    max-width: 600px;
    width: 100%;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    position: relative;
  }
  .pet-detail p {
    margin: 8px 0;
    text-align: left;
}

  .close-btn {
    background-color: #f44336;
    color: white;
    padding: 10px 20px;
    border-radius: 6px;
    border: none;
    cursor: pointer;
    font-size: 16px;
    margin-bottom: 20px;
    margin-top: 10px;
  }

  .close-btn:hover {
    background-color: #d32f2f;
  }

  /* 响应式设计 */
  @media (max-width: 768px) {
    .filters {
      flex-direction: column;
    }

    .filters .filters-dropdown {
      flex: 1 1 100%;
    }

    .pet-card {
      padding: 15px;
    }
  }
  </style>